import multiprocessing
import gunicorn.app.base
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def number_of_workers():
    return (multiprocessing.cpu_count() * 2) + 1

class StandaloneApplication(gunicorn.app.base.BaseApplication):
    def __init__(self, app, options=None):
        self.options = options or {}
        self.application = app
        super().__init__()

    def load_config(self):
        config = {key: value for key, value in self.options.items()
                 if key in self.cfg.settings and value is not None}
        for key, value in config.items():
            self.cfg.set(key.lower(), value)

    def load(self):
        return self.application

def init_app():
    """初始化应用"""
    try:
        from face_search_service import app
        # 测试 Milvus 连接
        from face_searcher_milvus import FaceSearcherMilvus
        searcher = FaceSearcherMilvus()
        logger.info("应用初始化成功")
        return app
    except Exception as e:
        logger.error(f"应用初始化失败: {str(e)}")
        raise

if __name__ == '__main__':
    try:
        app = init_app()
        
        options = {
            'bind': '0.0.0.0:8000',
            'workers': number_of_workers(),
            'worker_class': 'uvicorn.workers.UvicornWorker',
            'timeout': 120,        # 增加超时时间
            'keepalive': 65,       # 增加保活时间
            'max_requests': 1000,
            'max_requests_jitter': 50,
            'errorlog': '-',
            'loglevel': 'info',
            'reload': True,
            # 添加以下配置
            'worker_connections': 1000,
            'backlog': 2048,
            'graceful_timeout': 120,
            'access_log_format': '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(L)s'
        }

        logger.info(f"启动服务器，配置: {options}")
        StandaloneApplication(app, options).run()
        
    except Exception as e:
        logger.error(f"服务启动失败: {str(e)}")
        raise 